<?php

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\models\datas\Cate;
use common\models\datas\CateAttr;
use doumiaoduo\buildform\BuildForm;
use yii\data\Sort;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsAttr;
use zhtfrontend\models\datas\Mechanic;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\data\Pagination;
use yii\helpers\Json;
use yii\web\BadRequestHttpException;
use zhtfrontend\models\datas\Course;
use yii\helpers\ArrayHelper;
use common\components\actions\DeleteAction;
use common\components\helpers\Tree;
use yii\widgets\ActiveForm;

class CourseController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        $mids = Fun::getMechanicIds();
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;

        $data = Course::find()->where(['status' => 1]);
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            if (!empty($search_data['category_name'])) {
                $category = Cate::find()->select('id')->where(['like', 'name', $search_data['category_name']])->column();
                $data->andWhere(['in', 'category_id', $category]);
            }
            if (!empty($search_data['name'])) {
                $data->andWhere(['like', 'name', $search_data['name']]);
            }
            if (!empty($search_data['mechanic_name'])) {
                $ids = Mechanic::find()->select('id')->where(['like', 'name', $search_data['mechanic_name']])->column();
                $data->andWhere(['mechince_id' => $ids]);
            }
            if (!empty($search_data['teache_form'])) {
                $data->andWhere(['teache_form' => $search_data['teache_form']]);
            }

        }
        $data->orderBy('mechince_id ASC');
        if (!empty($mids)) {
            $data->andWhere(['mechince_id' => $mids]);
        }
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'class_director') {
            $admin_id = \Yii::$app->user->id;
            $mechanic_id = Mechanic::find()->select('id')->where(['admin_id' => $admin_id, 'is_delete' => 0])->column();
            $data->andWhere(['mechanic_id' => $mechanic_id]);
        }
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'category') {
            $data->andWhere(['type_id' => \Yii::$app->user->identity->type_id]);
        }
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $array = Fun::asArray($model, ['admin', 'mechanic_name', 'category_name', 'operate']);

        return $this->render('index', ['data' => $array, 'pages' => $pages]);
    }

    public function actionCreate()
    {
        $this->layout = false;
        $mids = Fun::getMechanicIds(); //获取机构以及子机构id
        $model = new Course();
        $model->scenario = 'create';
        $form = new BuildForm('@app/components/forms/courseForm.php');
        $form->loadModel(['course' => $model]);
        $form->loadDefaultValues();

        $cat_ids = CateAttr::find()->select('cat_id')->where(['site_id' => Fun::getSiteId()])->column();
        $categorys = Cate::find()->where(['id' => $cat_ids, 'type_id' => 1, 'is_delete' => 0])->indexBy('id')->orderby('sort ASC')->all();
        $tree = (new Tree($categorys))->get_tree_select();
//        $form->setItems('course','category_id',$tree);
        $form->setData('course', 'category_id', 'data', $tree);
        $mechanicModel = Mechanic::find()->where(['site_id' => Fun::getSiteId(), 'is_delete' => 0, 'status' => 1]);
        if (!empty($mids)) {
            $mechanicModel->andWhere(['id' => $mids]);//这个地方是如果是有机构id传过来，那么可以选择的有当前的机构或者是找个机构的子类
        }
        $mechanic = $mechanicModel->indexBy('id')->all();
        if (count($mechanic) == 1) {
            foreach ($mechanic as $key => $val) {
                $model->mechince_id = $key;
            }
            $tree_mechanic = ArrayHelper::map($mechanic, 'id', 'name');
        } else {
            $tree_mechanic = (new Tree($mechanic))->get_tree_select();
        }
        $form->setItems('course', 'mechince_id', $tree_mechanic);
        $admin_role = 0;
        if (\Yii::$app->user->identity->role == 'educational_administration' || \Yii::$app->user->identity->role == 'administrator' || \Yii::$app->user->identity->role == 'admin') {
            $admin_role = 1;
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'course-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $model->site_id = Fun::getSiteId();
            $model->user_id = \Yii::$app->user->id;
            if ($model->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '课程添加成功'), Fun::url('course/index'));
            }
        }
        return $this->render('create', ['form' => $form->render(), 'admin_role' => $admin_role]);
    }

    public function actionUpdate()
    {
        $this->layout = false;
        $mids = Fun::getMechanicIds(); //获取机构以及子机构id
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Course::findOne(\Yii::$app->request->get('id'));
        if ($model === null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model->scenario = 'update';
        $form = new BuildForm('@app/components/forms/courseForm.php');
        $form->loadModel(['course' => $model]);
        $cat_ids = CateAttr::find()->select('cat_id')->where(['site_id' => Fun::getSiteId()])->column();
        $categorys = Cate::find()->where(['id' => $cat_ids, 'type_id' => 1, 'is_delete' => 0])->indexBy('id')->orderBy('sort ASC')->all();
        $tree = (new Tree($categorys))->get_tree_select();
        $form->setData('course', 'category_id', 'data', $tree);
        $mechanicModel = Mechanic::find()->where(['site_id' => Fun::getSiteId(), 'is_delete' => 0, 'status' => 1]);
        if (!empty($mids)) {
            $mechanicModel->andWhere(['id' => $mids]);
        }
        $mechanic = $mechanicModel->all();
        $form->setItems('course', 'mechince_id', ArrayHelper::map($mechanic, 'id', 'name'));
        $admin_role = 0;
        if (\Yii::$app->user->identity->role == 'educational_administration' || \Yii::$app->user->identity->role == 'administrator' || \Yii::$app->user->identity->role == 'admin') {
            $admin_role = 1;
        }
        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'course-form' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            if ($model->save(false)) {
                $goods_attr = GoodsAttr::find()->where(['obj_type' => 'course', 'attribute_id' => $model->id])->all();
                if (isset($goods_attr)) {
                    foreach ($goods_attr as $k => $v) {
                        $goods = Goods::findOne(['id' => $v->goods_id]);
                        $goods->content = $model->description;
                        $goods->save(false);
                        $goods_attr_model = GoodsAttr::find()->where(['goods_id' => $v->goods_id, 'obj_type' => 'teacher_form'])->all();
                        foreach ($goods_attr_model as $key => $val) {
                            $val->value = $model->teache_form;
                            $val->save(false);
                        }
                        /*if($goods->save(false)){
                            return $this->redirectMessage(\Yii::t('zhtfrontend','信息修改成功'),Fun::url('course/index'));
                        }*/
                    }
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '信息修改成功'), Fun::url('course/index'));
                }
            }
        }
        return $this->render('create', ['form' => $form->render(), 'admin_role' => $admin_role]);
    }

    public function actions()
    {
        return [
            'delete' => [
                'class' => DeleteAction::className(),
                'modelClass' => Course::className(),
                'message' => ['success' => '删除成功！'],
                'redirectTo' => 'course/index',
            ],
        ];
    }
}
